package shell

import (
	"bytes"
	"os/exec"
	"strings"
)

func init() {

}

// Excute 执行cmd指令并返回执行状态和结果信息
func Exec(cmd string) (bool, string) {
	branches := strings.Split(cmd, " ")
	CMD := exec.Command(branches[0], branches[1:]...)
	var stdout, stderr bytes.Buffer
	CMD.Stdout = &stdout
	CMD.Stderr = &stderr
	err := CMD.Run()
	outStr, errStr := stdout.String(), stderr.String()
	if err != nil {
		return false, errStr
	}
	return true, outStr
}

func ExecOnDir(cmd string, path string) (bool, string) {
	branches := strings.Split(cmd, " ")
	CMD := exec.Command(branches[0], branches[1:]...)
	CMD.Dir = path
	var stdout, stderr bytes.Buffer
	CMD.Stdout = &stdout
	CMD.Stderr = &stderr
	err := CMD.Run()
	outStr, errStr := stdout.String(), stderr.String()
	if err != nil {
		return false, errStr
	}
	return true, outStr
}

func ExecWithOption(cmd string) (bool, string) {
	// branches := strings.Split(cmd, " ")
	CMD := exec.Command("bash", "-c", cmd)
	var stdout, stderr bytes.Buffer
	CMD.Stdout = &stdout
	CMD.Stderr = &stderr
	err := CMD.Run()
	outStr, errStr := stdout.String(), stderr.String()
	if err != nil {
		return false, errStr
	}
	return true, outStr
}

func ExecOnDirWithOption(cmd string, path string) (bool, string) {
	// branches := strings.Split(cmd, " ")
	CMD := exec.Command("bash", "-c", cmd)
	CMD.Dir = path
	var stdout, stderr bytes.Buffer
	CMD.Stdout = &stdout
	CMD.Stderr = &stderr
	err := CMD.Run()
	outStr, errStr := stdout.String(), stderr.String()
	if err != nil {
		return false, errStr
	}
	return true, outStr
}
